//
//  ChangeHeadImgViewController.m
//  QRMaster
//
//  Created by myApple on 15/6/30.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "ChangeHeadImgViewController.h"
#import "OpertionPlist.h"
#import "RequestNetWork.h"
#import "UIImageView+WebCache.h"
#import "PromptInfoView.h"
//#import "StartPageController.h"
#import "AdjuestViewController.h"
#import "AFHTTPRequestOperationManager.h"
@interface ChangeHeadImgViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,AdjuestViewControllerDelegate>
{
    UIScrollView * headerImgScrollView;
    NSMutableArray * headerImgData;
    NSUserDefaults * userInfo;
    BOOL gitPicFromNetworkOrlocal;//yes表示从网络请求，no表示从本地请求
    UIImageView * previewImgView;//预览图片
    
    NSInteger imgIndex;//记住选择的是第几张图片
    UIImageView * logoActivityView;
    
    //多语言
    UILabel * titleNameLabel;
    NSArray * sectionArray;
    UIButton * saveImgBtn;
}

@end

@implementation ChangeHeadImgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    imgIndex = 1000;
    headerImgData = [[NSMutableArray alloc]init];
    userInfo = [NSUserDefaults standardUserDefaults];
    [self prepareTitleView];
    [self getData];
    [self PreparePreview];
    [self prepareActivityIndicator];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    titleNameLabel.text = NSLocalizedString(@"chooseTitleImg", nil);
    [saveImgBtn setTitle:NSLocalizedString(@"save", nil) forState:0];
    sectionArray = @[NSLocalizedString(@"manSystem", nil),NSLocalizedString(@"womanSystem", nil)];
    saveImgBtn.hidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationItem.title = NSLocalizedString(@"chooseTitleImg", nil);
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    saveImgBtn.hidden = YES;
    
}
-(void)prepareTitleView
{
    saveImgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveImgBtn.frame = CGRectMake(UI_SCREEN_WIDTH - 60, 15, 40, 14);
    [saveImgBtn setTitle:NSLocalizedString(@"save", nil) forState:0];
    [saveImgBtn setTitleColor:[UIColor whiteColor] forState:0];
    [saveImgBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:saveImgBtn];
}

//预览
-(void)PreparePreview
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight / 5.0;
    UIImageView * PreviewView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    PreviewView.image = [UIImage imageNamed:@"headerImg"];
    PreviewView.userInteractionEnabled = YES;
    [self.view addSubview:PreviewView];
    
    x = ScreenWidth / 2.0 - 38;
    y = PreviewView.frame.size.height / 2.0 - 38;
    width = 76;
    height = 76;
    UIView * titleViewBackColor = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    titleViewBackColor.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.5];
    titleViewBackColor.layer.cornerRadius = 38;
    titleViewBackColor.layer.masksToBounds = YES;
    [PreviewView addSubview:titleViewBackColor];
    
    x = ScreenWidth / 2.0 - 29;
    y = PreviewView.frame.size.height / 2.0 - 29;
    width = 58;
    height = 58;
    previewImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [previewImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERURL,_imageUrlPath]] placeholderImage:[UIImage imageNamed:@"96人像"]];
    previewImgView.layer.cornerRadius = 29;
    previewImgView.layer.masksToBounds = YES;
    [PreviewView addSubview:previewImgView];
    
    //选择相机
    UIButton * cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    x = 0;
    width = PreviewView.frame.size.width / 2 - 38;
    y = PreviewView.frame.size.height / 2 - 10;
    height = 20;
    cameraBtn.frame = CGRectMake(x, y, width, height);
    [cameraBtn setTitle:NSLocalizedString(@"takePhoto", nil) forState:0];
    [cameraBtn addTarget:self action:@selector(getImageFromCamera) forControlEvents:UIControlEventTouchUpInside];
    [PreviewView addSubview:cameraBtn];
    
    
    //选择相册
    UIButton * PhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    x += width + 76;
    width = PreviewView.frame.size.width / 2 - 38;
    PhotoBtn.frame = CGRectMake(x, y, width, height);
    [PhotoBtn setTitle:NSLocalizedString(@"getPhotoFromAlbum", nil) forState:0];
    [PhotoBtn addTarget:self action:@selector(getImageFromPhoto) forControlEvents:UIControlEventTouchUpInside];
    [PreviewView addSubview:PhotoBtn];
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, PreviewView.frame.size.height + PreviewView.frame.origin.y, ScreenWidth, 1)];
    lineView.backgroundColor = [UIColor colorWithRed:127 /255.0 green:127 /255.0 blue:127 /255.0 alpha:1];
    [self.view addSubview:lineView];
}

-(void)prepareHeaderImgView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0 + ScreenHeight / 5.0;
    float width = ScreenWidth;
    float height = ScreenHeight - y - 64;
    
    headerImgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    headerImgScrollView.showsVerticalScrollIndicator = NO;
    headerImgScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headerImgScrollView];
    float labelHeight = 0;
    NSInteger count = headerImgData.count;
    sectionArray = @[NSLocalizedString(@"manSystem", nil),NSLocalizedString(@"womanSystem", nil)];
    for (int i = 0 ; i < count; i++) {
        //view
        if (i == 0 || i == 10) {

            if (i == 0) {
                y = 0;
            }
            else
            {
                y += height;
            }
            labelHeight = 30;
            UIView * sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, y, ScreenWidth, labelHeight)];
            sectionView.backgroundColor = [UIColor whiteColor];
            [headerImgScrollView addSubview:sectionView];
            //线条
            UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, y + labelHeight, ScreenWidth, 1)];
            lineView.backgroundColor = [UIColor colorWithRed:216/255.0 green:216/255.0 blue:216/255.0 alpha:1];
          
            [headerImgScrollView addSubview:lineView];


            //label
            UILabel * sectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, width,20)];
            sectionLabel.text = sectionArray[i / 10];
            sectionLabel.textColor = RGBA(95, 95, 95, 1);
            sectionLabel.font = [UIFont systemFontOfSize:14.0];
            [sectionView addSubview:sectionLabel];
        }
        //图像
        NSString * headerUrl = headerImgData[i];
        width = (ScreenWidth- 4) / 3.0;
        height = width;
        y = i / 3 * (height +1) + labelHeight + 3 ;
        x = i % 3 * (width + 1) + 1;
        if (i >= 10) {
            y = (i + 2) / 3 * (height + 1) + 2 * (labelHeight + 3 );
            x = (i + 2) % 3 * (width + 1) + 1;
        }
        
        UIImageView * headerImgView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, width,height)];
        if (gitPicFromNetworkOrlocal) {
            NSString * url = [NSString stringWithFormat:@"%@%@",HEADERURL,headerUrl];
            [headerImgView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"96人像"]];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
            NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", i]];   // 保存文件的名称
            NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            if (data) {
                UIImage * image = [UIImage imageWithData:data];
                [UIImagePNGRepresentation(image)writeToFile:filePath atomically:YES];
            }
//            [UIImagePNGRepresentation(headerImgView.image)writeToFile:filePath atomically:YES];
            
        }
        else
        {
            //从本地读区图片
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
            NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", i]];   // 取出文件的名称
            UIImage *img = [UIImage imageWithContentsOfFile:filePath];
            headerImgView.image = img;
        }
        
        headerImgView.tag = 1800 + i;
        headerImgView.userInteractionEnabled = YES;
        UITapGestureRecognizer * headerImgTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headerImgClick:)];
        [headerImgView addGestureRecognizer:headerImgTap];
        [headerImgScrollView addSubview:headerImgView];
    }
    headerImgScrollView.contentSize = CGSizeMake(ScreenWidth, y + height);
}


-(void)getData
{
    [headerImgData removeAllObjects];
    //先从文件中读取，如果有就读取，不行就从网络请求
    NSMutableDictionary * dict = [OpertionPlist readDataFromPlist];
    headerImgData = [dict objectForKey:HEADERIMG];
    if (headerImgData == nil) {
        [logoActivityView startAnimating];
        RequestNetWork * rnk = [[RequestNetWork alloc]init];
        NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
        [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
        [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
        [rnk initWithPath:POST(GETHEADERIMG) params:postDict block:^(id downLoadData, id error) {
            if ([downLoadData objectForKey:@"data"] != nil) {
                [logoActivityView stopAnimating];
                //请求下来的内容进行存文件(存的是文件路径)
                headerImgData = [downLoadData objectForKey:@"data"];
                NSMutableDictionary * headImgDict = [OpertionPlist readDataFromPlist];
                [headImgDict setValue:headerImgData forKey:HEADERIMG];
                [OpertionPlist writeDataToPlist:headImgDict];
                gitPicFromNetworkOrlocal = YES;//表示从网络请求的图片
                [self prepareHeaderImgView];
                
            }
            else if (error != nil) {
                
                
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }

        }];

    }
    else
    {
        [self prepareHeaderImgView];
        gitPicFromNetworkOrlocal = NO;//从本地获取图片
    }
    
}

#pragma mark -- 改变头像
-(void)headerImgClick:(UITapGestureRecognizer *)tap
{
    imgIndex = tap.view.tag - 1800;
    //从本地读区图片
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld.png", (long)imgIndex]];   // 取出文件的名称
    UIImage *img = [UIImage imageWithContentsOfFile:filePath];
    previewImgView.image = img;

}

#pragma mark -- 保存图片
-(void)saveClick
{
    if (imgIndex == 1000) {
        [PromptInfoView showMessage:NSLocalizedString(@"chooseHeaderImage", @"请选择头像") superView:self.view];
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSString * headerUrl = headerImgData[imgIndex];
     RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:headerUrl forKey:@"headpath"];
    [rnk initWithPath:POST(MODIFYHEADERIMG) params:postDict block:^(id downLoadData, id error) {
        
        [self stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil) {
            [self anlaylisSetHead];
            
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
 
    }];
 
}

-(void)anlaylisSetHead
{
    if (_selectImgPath) {
        _selectImgPath(imgIndex);
    }
    imgIndex = 1000;
    [self BackClick];
}

#pragma mark ---拍照
-(void)getImageFromCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark --从相册中获取

-(void)getImageFromPhoto
{
    UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = NO;
    [self presentViewController:pickerImage animated:YES completion:nil];
    
}

#pragma mark -- 选择照片或者照相完后触发的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    AdjuestViewController * advc = [[AdjuestViewController alloc]init];
    advc.image = image;
    advc.aduestViewDelegate = self;
//    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary || picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
//        UIImage * smallImg = [self imageWithImageSimple:image scaledToSize:CGSizeMake(60, 60)];
//        UIImage * midImg = [self imageWithImageSimple:image scaledToSize:CGSizeMake(120, 120)];
//        UIImage * bigImg =[self imageWithImageSimple:image scaledToSize:CGSizeMake(180, 180)];
//        
//        [self saveImage:smallImg withName:@"smallImage.png"];
//        [self saveImage:midImg withName:@"middleImage.png"];
//        [self saveImage:bigImg withName:@"bigImage.png"];
//        previewImgView.image = smallImg;
//    }
    [picker dismissViewControllerAnimated:NO completion:nil];
//    [picker presentViewController:advc animated:YES completion:nil];
    [self presentViewController:advc animated:YES completion:nil];
}

#pragma mark adjuestDelegate
-(void)AdjuestSendImage:(UIImage *)newImage
{
    previewImgView.image = newImage;
    NSData *imageData = UIImageJPEGRepresentation(newImage, 1);
    [self upLoadPhoto:imageData];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//压缩图片
-(UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//保存图片
-(void)saveImage:(UIImage *)tempImage withName:(NSString *)imageName
{
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSData * imageData = UIImagePNGRepresentation(tempImage);
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * pathToFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"SelfPicture/"]];
    if (![[NSFileManager defaultManager]fileExistsAtPath:pathToFile]) {
        [fileManager createDirectoryAtPath:pathToFile withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString * fullFilePath = [pathToFile stringByAppendingPathComponent:imageName];
    [imageData writeToFile:fullFilePath atomically:NO];
    
}

-(void)BackClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)prepareActivityIndicator
{
    logoActivityView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2.0 -15, self.view.frame.size.height/2.0 - 15, 30, 30)];
    [self.view addSubview:logoActivityView];
    logoActivityView.animationImages = [NSArray arrayWithObjects:
                                        [UIImage imageNamed:@"2"],
                                        [UIImage imageNamed:@"3"],
                                        [UIImage imageNamed:@"4"],
                                        [UIImage imageNamed:@"5"],
                                        [UIImage imageNamed:@"6"],
                                        [UIImage imageNamed:@"7"],
                                        [UIImage imageNamed:@"8"],
                                        [UIImage imageNamed:@"9"],
                                        nil];
    logoActivityView.animationDuration = 1.0;
    logoActivityView.animationRepeatCount = 0;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//上传头像
-(void)upLoadPhoto:(NSData *)data
{
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:UID forKey:@"id"];
    [postDict setValue:TOKEN forKey:@"token"];
    

    AFHTTPRequestOperationManager *mgr=[AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [mgr POST:[NSString stringWithFormat:@"%@%@?id=%@&token=%@",HEADERURL,UPLOADPHOTO,[self encodeToPercentEscapeString:[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]],[self encodeToPercentEscapeString:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]]] parameters:postDict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:data name:@"file" fileName:@"photo.jpg" mimeType:@"image/jpg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        [PromptInfoView showMessage:[obj objectForKey:@"info"] superView:self.view];
        if (self.postImgPath) {
            self.postImgPath([[obj objectForKey:@"data"] objectForKey:@"headurl"]);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        if ([error.userInfo objectForKey:ERRORINFO]) {
            id obj = [NSJSONSerialization JSONObjectWithData:[error.userInfo objectForKey:ERRORINFO] options:NSJSONReadingMutableContainers error:nil];
           [PromptInfoView showMessage:[obj objectForKey:@"info"] superView:self.view];
        }
    }];

}
- (NSString *)encodeToPercentEscapeString: (NSString *) input
{
    NSString *outputStr = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (CFStringRef)input,
                                            NULL,
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8));
    return outputStr;
}

- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end
